﻿using System;
using System.Collections.Generic;
using System.Configuration ;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BoYuanCore.CodeGenerator.code;
using FineUIPro;

namespace BoYuanCore.CodeGenerator
{
    public partial class DbConfig : CodeBasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    if (Session["dbtype"] != null)
                    {
                        ddl_db.SelectedValue = Session["dbtype"].ToString();
                    }

                    if (Session["db"] != null)
                    {
                        ttbDB.Text = Session["db"].ToString();
                        BindTable();
                    }
                    else
                    {
                        ttbDB.Text = ConfigurationManager.AppSettings["ConnectionString"];
                    }
                }
                catch (Exception exception)
                {
                    NotifyError("连接异常:" + exception.Message);
                }
            }
        }

        protected void BindDB()
        {
            Session["db"] = ttbDB.Text;
            Session["dbtype"] = ddl_db.SelectedValue;

            try
            {
                var data = GetTableInfos();
                if (data == null || data.Count == 0)
                {
                    AlertError("获取不到数据库的table", false);
                    return;
                }

                Session["db"] = ttbDB.Text;
            }
            catch (Exception exception)
            {
                AlertError("连接数据库异常：" + exception.Message, false);
                return;
            }
            //PageContext.RegisterStartupScript("parent.RefreshTables();");
            BindTable();
        }

        private void BindTable()
        {
            if (Session["db"] == null)
            {
                AlertError("请先连接数据库", false);
                return;
            }
            var data = GetTableInfos(ttbSearchTableName.Text);
            cbl_tables.BindByDataSource(data, "name", "name");
        }


        protected void btn_DBlink_OnClick(object sender, EventArgs e)
        {
            BindDB();
        }

        protected void ttbSearchTableName_OnTrigger1Click(object sender, EventArgs e)
        {
            BindTable();
        }

        protected void ttbSearchTableName_OnTrigger2Click(object sender, EventArgs e)
        {
            BindTable();
        }

        protected void btn_RefreshTables_OnClick(object sender, EventArgs e)
        {
            BindDB();
        }

    }
}